<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="选择指定优惠券" extra="请先确保优惠券剩余数量充足，否则将会导致发送失败">
          <a-button @click="couponShow = true">选择优惠券</a-button>
          <!-- 选中优惠券列表 -->
          <a-table v-if="couponSource1.length > 0" :dataSource="couponSource1" rowKey="coupon_id"
            :columns="couponColumns1" :loading="isLoading" :pagination="false">
            <!-- 最低消费金额 -->
            <template slot="min_price" slot-scope="text">
              <p class="c-p">¥{{ text }}</p>
            </template>
            <!-- 优惠方式 -->
            <template slot="discount" slot-scope="item">
              <template v-if="item.coupon_type == 10">
                <span>立减</span>
                <span class="c-p mlr-2">¥{{ item.reduce_price }}</span>
              </template>
              <template v-if="item.coupon_type == 20">
                <span>打</span>
                <span class="c-p mlr-2">{{ item.discount }}</span>
                <span>折</span>
              </template>
            </template>
            <!-- 操作 -->
            <span class="actions" slot="action" slot-scope="item">
              <a @click="couponDelete()">删除</a>
            </span>
          </a-table>
        </a-form-item>

        <a-form-item label="选择用户">
          <a-button @click="userShow = true">选择用户</a-button>
          <!-- 选中优惠券列表 -->
          <a-table v-if="userSource1.length > 0" :dataSource="userSource1" rowKey="user_id" :columns="userColumns1"
            :loading="isLoading" :pagination="false">
            <!-- 会员头像 -->
            <span slot="avatar_url" slot-scope="text">
              <div class="avatar">
                <img v-if="text" width="45" height="45" :src="text" alt="用户头像" />
                <img v-else width="45" height="45" src="~@/assets/img/default-avatar.png" alt="用户头像" />
              </div>
            </span>
            <span slot="main_info" slot-scope="item">
              <p>{{ item.nick_name }}</p>
              <p class="c-p">{{ item.mobile }}</p>
            </span>
            <!-- 余额/积分 -->
            <span slot="balance" slot-scope="text, item">
              <p>
                <span>余额：</span>
                <span class="c-p">{{ text }}</span>
              </p>
              <p>
                <span>积分：</span>
                <span class="c-p">{{ item.points }}</span>
              </p>
            </span>
            <!-- 实际消费金额 -->
            <span slot="expend_money" slot-scope="text">
              <span class="c-p">{{ text }}</span>
            </span>
            <!-- 操作 -->
            <span class="actions" slot="action" slot-scope="item">
              <a @click="userDelete()">删除</a>
            </span>
          </a-table>
        </a-form-item>
        <a-form-item class="mt-20" :wrapperCol="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit" :loading="isBtnLoading">提交</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
    <!-- 选择优惠券弹窗 -->
    <a-modal title="选择优惠券" centered :width="1400" :visible="couponShow" @cancel="couponCancel" @ok="couponSubmit">
      <a-input-search style="width: 200px;margin-bottom: 20px;" v-model="couponName" placeholder="请输入优惠券名称"
        @search="couponSearch" />
      <a-table :dataSource="couponSource" rowKey="coupon_id" :columns="couponColumns" :pagination="couponPagination"
        :loading="isLoading" @change="couponChange" :row-selection="couponSelection">
        <!-- 优惠券类型 -->
        <template slot="coupon_type" slot-scope="text">
          <a-tag>{{ CouponTypeEnum[text].name }}</a-tag>
        </template>
        <!-- 最低消费金额 -->
        <template slot="min_price" slot-scope="text">
          <p class="c-p">¥{{ text }}</p>
        </template>
        <!-- 优惠方式 -->
        <template slot="discount" slot-scope="item">
          <template v-if="item.coupon_type == 10">
            <span>立减</span>
            <span class="c-p mlr-2">¥{{ item.reduce_price }}</span>
          </template>
          <template v-if="item.coupon_type == 20">
            <span>打</span>
            <span class="c-p mlr-2">{{ item.discount }}</span>
            <span>折</span>
          </template>
        </template>
        
        <!-- 发放总数量/已发放 -->
        <template slot="receive_num" slot-scope="item">
          {{ item.total_num }}/{{ item.receive_num }}
        </template>
        <!-- 有效期 -->
        <template slot="duetime" slot-scope="item">
          <template v-if="item.expire_type == 10">
            <span>领取</span>
            <span class="c-p mlr-2">{{ item.expire_day }}</span>
            <span>天内有效</span>
          </template>
          <template v-if="item.expire_type == 20">
            <span>{{ item.start_time }} ~ {{ item.end_time }}</span>
          </template>
        </template>
        <!-- 状态 -->
        <template slot="status" slot-scope="text">
          <a-tag :color="text ? 'green' : ''">{{ text ? '显示' : '隐藏' }}</a-tag>
        </template>
      </a-table>
    </a-modal>

    <!-- 选择用户弹窗 -->
    <a-modal title="选择用户" centered :width="1400" :visible="userShow" @cancel="userCancel" @ok="userSubmit">
      <a-input-search style="width: 200px;margin-bottom: 20px;" v-model="userName" placeholder="请输入用户名称"
        @search="userSearch" />
      <a-table :dataSource="userSource" rowKey="user_id" :columns="userColumns" :pagination="userPagination"
        :loading="isLoading" @change="userChange" :row-selection="userSelection">
        <!-- 会员头像 -->
        <span slot="avatar_url" slot-scope="text">
          <div class="avatar">
            <img v-if="text" width="45" height="45" :src="text" alt="用户头像" />
            <img v-else width="45" height="45" src="~@/assets/img/default-avatar.png" alt="用户头像" />
          </div>
        </span>
        <span slot="main_info" slot-scope="item">
          <p>{{ item.nick_name }}</p>
          <p class="c-p">{{ item.mobile }}</p>
        </span>
        <!-- 余额/积分 -->
        <span slot="balance" slot-scope="text, item">
          <p>
            <span>余额：</span>
            <span class="c-p">{{ text }}</span>
          </p>
          <p>
            <span>积分：</span>
            <span class="c-p">{{ item.points }}</span>
          </p>
        </span>
        <!-- 实际消费金额 -->
        <span slot="expend_money" slot-scope="text">
          <span class="c-p">{{ text }}</span>
        </span>
      </a-table>
    </a-modal>
  </a-card>
</template>

<script>
import * as CouponApi from '@/api/market/coupon'//优惠券
import * as UserApi from '@/api/user' //用户
import { message } from 'ant-design-vue';

import { ApplyRangeEnum, CouponTypeEnum, ExpireTypeEnum } from '@/common/enum/coupon'

export default {
  data() {
    return {
      // 正在加载
      isLoading: false,
      isBtnLoading: false,
      // 标签布局属性
      labelCol: { span: 3 },
      // 输入框布局属性
      wrapperCol: { span: 10 },
      // 当前表单元素
      form: this.$form.createForm(this),

      CouponTypeEnum,

      //优惠券开关
      couponShow: false,
      // 优惠券搜索
      couponName: '',
      // 优惠券表头
      couponColumns: [
        {
          title: '优惠券ID',
          dataIndex: 'coupon_id'
        },
        {
          title: '优惠券名称',
          dataIndex: 'name'
        },
        {
          title: '优惠券类型',
          dataIndex: 'coupon_type',
          scopedSlots: { customRender: 'coupon_type' }
        },
        {
          title: '最低消费金额 (元)',
          dataIndex: 'min_price',
          scopedSlots: { customRender: 'min_price' }
        },
        {
          title: '优惠方式',
          scopedSlots: { customRender: 'discount' }
        },
        {
          title: '有效期',
          scopedSlots: { customRender: 'duetime' }
        },
        {
          title: '发放总数量/已发放',
          align: 'center',
          scopedSlots: { customRender: 'receive_num' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        }
      ],
      // 优惠券数组
      couponSource: [],
      // 优惠券分页
      couponPagination: {
        current: 1,
        total: 0, // 总数据量
        pageSize: 10, // 每页显示条数
        showQuickJumper: true, // 是否可以快速跳转
      },
      // 选中优惠券id数组
      couponRowKeys: [],
      // 选中优惠券表头
      couponColumns1: [{
        title: '优惠券ID',
        dataIndex: 'coupon_id'
      },
      {
        title: '优惠券名称',
        dataIndex: 'name'
      }, {
        title: '最低消费金额 (元)',
        dataIndex: 'min_price',
        scopedSlots: { customRender: 'min_price' }
      },
      {
        title: '优惠方式',
        scopedSlots: { customRender: 'discount' }
      }, {
        title: '操作',
        width: '180px',
        scopedSlots: { customRender: 'action' }
      }],
      // 选中优惠券数组
      couponSource1: [],
      // 选中优惠券id
      chooseCouponId: null,


      //用户开关
      userShow: false,
      // 用户搜索
      userName: '',
      // 用户表头
      userColumns: [
        {
          title: '会员ID',
          dataIndex: 'user_id'
        },
        {
          title: '会员头像',
          dataIndex: 'avatar_url',
          scopedSlots: { customRender: 'avatar_url' }
        },
        {
          title: '昵称/手机号',
          scopedSlots: { customRender: 'main_info' }
        },
        {
          title: '余额/积分',
          dataIndex: 'balance',
          scopedSlots: { customRender: 'balance' }
        },
        {
          title: '实际消费金额',
          dataIndex: 'expend_money',
          scopedSlots: { customRender: 'expend_money' }
        },
        {
          title: '注册时间',
          dataIndex: 'create_time'
        }
      ],
      // 用户数组
      userSource: [],
      // 用户分页
      userPagination: {
        current: 1,
        total: 0, // 总数据量
        pageSize: 10, // 每页显示条数
        showQuickJumper: true, // 是否可以快速跳转
      },
      // 选中用户id数组
      userRowKeys: [],
      // 选中用户表头
      userColumns1: [{
        title: '会员ID',
        dataIndex: 'user_id'
      },
      {
        title: '会员头像',
        dataIndex: 'avatar_url',
        scopedSlots: { customRender: 'avatar_url' }
      },
      {
        title: '昵称/手机号',
        scopedSlots: { customRender: 'main_info' }
      },
      {
        title: '操作',
        width: '180px',
        scopedSlots: { customRender: 'action' }
      }],
      // 选中用户数组
      userSource1: [],
      // 选中用户id
      chooseUserId: null,
    }
  },
  created() {
    // 优惠券列表
    this.getCoupon()
    // 用户列表
    this.getUser()
  },
  computed: {
    couponSelection() {
      return {
        type: 'radio',
        selectedRowKeys: this.couponRowKeys,
        onChange: (selectedRowKeys) => {
          this.couponRowKeys = selectedRowKeys;
        },
      };
    },
    userSelection() {
      return {
        type: 'radio',
        selectedRowKeys: this.userRowKeys,
        onChange: (selectedRowKeys) => {
          this.userRowKeys = selectedRowKeys;
        },
      };
    },
  },
  methods: {
    // 优惠券列表
    getCoupon() {
      CouponApi.list({
        per_page: this.couponPagination.pageSize,
        page: this.couponPagination.current,
        search: this.couponName
      })
        .then(result => {
          this.couponSource = result.data.list.data
          this.couponPagination.total = result.data.list.total
        })
        .finally(() => this.isLoading = false)
    },
    // 优惠券列表
    getUser() {
      UserApi.list({
        per_page: this.userPagination.pageSize,
        page: this.userPagination.current,
        search: this.userName
      })
        .then(result => {
          this.userSource = result.data.list.data
          this.userPagination.total = result.data.list.total
        })
        .finally(() => this.isLoading = false)
    },

    //优惠券弹窗关闭
    couponCancel() {
      this.couponShow = false
    },

    //优惠券弹窗ok
    couponSubmit() {
      this.chooseCouponId = this.couponRowKeys[0]
      this.couponSource1 = this.couponSource.filter(item => this.couponRowKeys.includes(item.coupon_id));
      this.couponCancel()
    },

    // 优惠券弹窗分页
    couponChange(pagination, filters, sorter) {
      this.couponPagination.current = pagination.current
      this.getCoupon()
    },

    //选择优惠券(弹窗中优惠券搜索按钮)
    couponSearch(e) {
      this.couponName = e
      this.couponPagination.current = 1
      this.getCoupon()  //采购商品列表
    },

    // 删除选中的优惠券
    couponDelete() {
      this.chooseCouponId = null
      this.couponSource1 = []
      this.couponRowKeys = []
    },


    //用户弹窗关闭
    userCancel() {
      this.userShow = false
    },

    //用户弹窗ok
    userSubmit() {
      this.chooseUserId = this.userRowKeys[0]
      this.userSource1 = this.userSource.filter(item => this.userRowKeys.includes(item.user_id));
      this.userCancel()
    },

    // 用户弹窗分页
    userChange(pagination, filters, sorter) {
      this.userPagination.current = pagination.current
      this.getUser()
    },

    //选择用户(弹窗中用户搜索按钮)
    userSearch(e) {
      this.userName = e
      this.userPagination.current = 1
      this.getUser()  //采购商品列表
    },

    // 删除选中的用户
    userDelete() {
      this.chooseUserId = null
      this.userSource1 = []
      this.userRowKeys = []
    },

    // 确认按钮
    handleSubmit(e) {
      //查看数组时候已经添加过这个规格的商品了
      if (!this.chooseCouponId) {
        message.error('请选择指定优惠券');
      } else if (!this.chooseUserId) {
        message.error('请选择用户');
      } else {
        this.onFormSubmit()
      }
    },

    // 提交到后端api
    onFormSubmit() {
      // this.isLoading = true
      this.isBtnLoading = true
      let form = {
        couponId: this.chooseCouponId,
        target: {
          userIds: this.userRowKeys
        },
        type: 10
      }
      CouponApi.give({form})
        .then(result => {
          // 显示提示信息
          this.$message.success(result.message, 1.5)

          this.couponDelete()//清空选中优惠券
          this.userDelete()//清空选中用户
          this.getCoupon()//刷新优惠券列表
        })
        .catch(() => this.isBtnLoading = false)
        .finally(() => this.isBtnLoading = false)
    }
  }
}
</script>
<style lang="less" scoped></style>
